package com.gzc.just.play.last.war.sceneserver.battle.service;

import com.gzc.just.play.last.war.sceneserver.battle.manager.EnhancedBattleSessionManager;
import com.gzc.just.play.last.war.sceneserver.battle.model.BattleInfo;
import com.gzc.just.play.last.war.sceneserver.battle.model.BattleRecord;
import com.gzc.just.play.last.war.sceneserver.battle.model.BattleUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 战斗业务服务层
 * 重构版本：使用EnhancedBattleSessionManager管理战斗会话
 * 处理战斗相关的业务逻辑
 */
@Service
public class BattleService {
    
    private static final Logger log = LoggerFactory.getLogger(BattleService.class);
    
    @Autowired
    private EnhancedBattleSessionManager enhancedBattleSessionManager;
    
    /**
     * 创建新的战斗
     */
    public BattleInfo createBattle(BattleInfo.BattleType battleType,
                                   Integer mapId,
                                   Integer maxPlayers,
                                   List<Long> team1Players,
                                   List<Long> team2Players) {
        BattleInfo battle = enhancedBattleSessionManager.createBattle(battleType, mapId, maxPlayers);
        
        battle.setTeam1Players(team1Players != null ? team1Players : new ArrayList<>());
        battle.setTeam2Players(team2Players != null ? team2Players : new ArrayList<>());
        
        log.info("创建战斗会话: battleId={}, type={}", battle.getBattleId(), battleType);
        
        return battle;
    }
    
    /**
     * 玩家加入战斗
     */
    public boolean joinBattle(Long battleId, Long userId, String nickname, Long characterId) {
        BattleInfo battle = enhancedBattleSessionManager.getBattleInfo(battleId);
        if (battle == null) {
            log.warn("战斗不存在: battleId={}", battleId);
            return false;
        }
        
        if (battle.isFull()) {
            log.warn("战斗已满: battleId={}", battleId);
            return false;
        }
        
        if (battle.getStatus() != BattleInfo.BattleStatus.WAITING) {
            log.warn("战斗状态不对，无法加入: battleId={}, status={}", battleId, battle.getStatus());
            return false;
        }
        
        // 创建用户信息
        BattleUserInfo userInfo = new BattleUserInfo();
        userInfo.setUserId(userId);
        userInfo.setNickname(nickname);
        userInfo.setCharacterId(characterId);
        // 注意：BattleUserInfo类没有setJoinTime方法，这个设置可能需要在其他地方处理
        
        // 将玩家加入战斗会话
        boolean success = enhancedBattleSessionManager.addPlayerToBattle(battleId, userInfo);
        
        if (success) {
            log.info("玩家加入战斗会话: userId={}, battleId={}", userId, battleId);
        } else {
            log.warn("玩家加入战斗失败: userId={}, battleId={}", userId, battleId);
        }
        
        return success;
    }
    
    /**
     * 玩家离开战斗
     */
    public boolean leaveBattle(Long userId) {
        BattleInfo battle = enhancedBattleSessionManager.getUserBattleInfo(userId);
        if (battle == null) {
            log.warn("玩家不在任何战斗中: userId={}", userId);
            return false;
        }
        
        Long battleId = battle.getBattleId();
        
        // 从战斗会话中移除玩家
        enhancedBattleSessionManager.removePlayerFromBattle(userId);
        
        log.info("玩家离开战斗会话: userId={}, battleId={}", userId, battleId);
        
        return true;
    }
    
    /**
     * 开始战斗
     */
    public boolean startBattle(Long battleId) {
        BattleInfo battle = enhancedBattleSessionManager.getBattleInfo(battleId);
        if (battle == null) {
            log.warn("战斗不存在: battleId={}", battleId);
            return false;
        }
        
        if (battle.getStatus() != BattleInfo.BattleStatus.WAITING) {
            log.warn("战斗状态不对，无法开始: battleId={}, status={}", battleId, battle.getStatus());
            return false;
        }
        
        if (battle.getPlayerCount() < 2) {
            log.warn("战斗人数不足，无法开始: battleId={}, playerCount={}", battleId, battle.getPlayerCount());
            return false;
        }
        
        // 开始战斗会话
        boolean success = enhancedBattleSessionManager.startBattle(battleId);
        
        if (success) {
            log.info("战斗开始: battleId={}", battleId);
        } else {
            log.warn("战斗开始失败: battleId={}", battleId);
        }
        
        return success;
    }
    
    /**
     * 结束战斗
     */
    public boolean endBattle(Long battleId) {
        BattleInfo battle = enhancedBattleSessionManager.getBattleInfo(battleId);
        if (battle == null) {
            log.warn("战斗不存在: battleId={}", battleId);
            return false;
        }
        
        // 结束战斗会话
        enhancedBattleSessionManager.endBattle(battleId);
        
        log.info("战斗结束: battleId={}", battleId);
        
        return true;
    }
    
    /**
     * 提交战斗操作
     */
    public boolean submitBattleAction(Long userId, int actionId, byte[] actionData) {
        BattleInfo battle = enhancedBattleSessionManager.getUserBattleInfo(userId);
        if (battle == null) {
            log.warn("玩家不在任何战斗中，无法提交操作: userId={}", userId);
            return false;
        }
        
        Long battleId = battle.getBattleId();
        
        // 提交操作到战斗会话
        boolean success = enhancedBattleSessionManager.submitBattleMessage(battleId, userId, actionId, actionData);
        
        if (!success) {
            log.warn("提交战斗操作失败: userId={}, battleId={}, actionId={}", userId, battleId, actionId);
        }
        
        return success;
    }
    
    /**
     * 获取战斗信息
     */
    public BattleInfo getBattleInfo(Long battleId) {
        return enhancedBattleSessionManager.getBattleInfo(battleId);
    }
    
    /**
     * 获取玩家所在的战斗信息
     */
    public BattleInfo getUserBattle(Long userId) {
        return enhancedBattleSessionManager.getUserBattleInfo(userId);
    }
    
    /**
     * 获取所有活跃战斗列表
     */
    public List<BattleInfo> getActiveBattles() {
        return enhancedBattleSessionManager.getActiveBattles();
    }
    
    /**
     * 获取战斗记录
     */
    public List<BattleRecord> getBattleRecords(Long battleId) {
        // 这里可以从数据库或其他存储中获取战斗记录
        // 暂时返回空列表
        return new ArrayList<>();
    }
    
    /**
     * 获取战斗统计信息
     */
    public Object getBattleStats(Long battleId) {
        BattleInfo battle = enhancedBattleSessionManager.getBattleInfo(battleId);
        if (battle == null) {
            return null;
        }
        
        // 构造统计信息
        java.util.Map<String, Object> stats = new java.util.HashMap<>();
        stats.put("battleId", battle.getBattleId());
        stats.put("battleType", battle.getBattleType());
        stats.put("mapId", battle.getMapId());
        stats.put("status", battle.getStatus());
        stats.put("playerCount", battle.getPlayerCount());
        stats.put("maxPlayers", battle.getMaxPlayers());
        stats.put("startTime", battle.getStartTime());
        stats.put("duration", battle.getDuration());
        
        return stats;
    }
    
    /**
     * 处理玩家断开连接
     */
    public void handlePlayerDisconnection(Long userId) {
        BattleInfo battle = enhancedBattleSessionManager.getUserBattleInfo(userId);
        if (battle != null) {
            Long battleId = battle.getBattleId();
            enhancedBattleSessionManager.removePlayerFromBattle(userId);
            log.info("玩家断开连接，从战斗中移除: userId={}, battleId={}", userId, battleId);
        }
    }
    
    /**
     * 记录玩家击杀
     */
    public boolean recordPlayerKill(Long attackerId, Long victimId) {
        try {
            // 获取攻击者和受害者信息
            BattleUserInfo attacker = getPlayerBattleStats(attackerId);
            BattleUserInfo victim = getPlayerBattleStats(victimId);
            
            if (attacker == null || victim == null) {
                log.warn("记录击杀失败：攻击者或受害者信息不存在 attackerId={}, victimId={}", 
                         attackerId, victimId);
                return false;
            }
            
            // 在实际实现中，这里应该更新战斗统计
            // 例如：增加击杀数、更新战绩等
            log.debug("记录玩家击杀：攻击者={}, 受害者={}", attackerId, victimId);
            return true;
        } catch (Exception e) {
            log.error("记录玩家击杀异常", e);
            return false;
        }
    }
    
    /**
     * 处理玩家受到伤害
     */
    public boolean playerTakeDamage(Long userId, Integer damage) {
        try {
            BattleUserInfo playerInfo = getPlayerBattleStats(userId);
            if (playerInfo == null) {
                log.warn("处理玩家伤害失败：玩家信息不存在 userId={}", userId);
                return false;
            }
            
            // 在实际实现中，这里应该处理玩家受伤逻辑
            // 例如：减少血量、检查死亡等
            log.debug("玩家受到伤害：userId={}, damage={}", userId, damage);
            return true;
        } catch (Exception e) {
            log.error("处理玩家伤害异常", e);
            return false;
        }
    }
    
    /**
     * 处理战斗心跳
     */
    public void processBattleHeartbeat() {
        enhancedBattleSessionManager.onHeartbeat();
    }
    
    /**
     * 获取活跃战斗数量
     */
    public int getActiveBattleCount() {
        return enhancedBattleSessionManager.getActiveBattleCount();
    }
    
    /**
     * 获取玩家战斗统计信息
     */
    public BattleUserInfo getPlayerBattleStats(Long userId) {
        BattleInfo battle = enhancedBattleSessionManager.getUserBattleInfo(userId);
        if (battle == null) {
            return null;
        }
        
        // 查找用户信息
        for (BattleUserInfo user : battle.getBattleUsers()) {
            if (user.getUserId().equals(userId)) {
                return user;
            }
        }
        
        return null;
    }
}